// dep: JSON Util persist
//
// store is from PeristJS
// id should match the id of the form
//
// persisted inputs should have class "durable"
// the id of the persisted inputs is the key
// this creates a namespace: form_id.input_id

var PersistForm = function( store, id ) {
	this.setStore = function( store ) {
		this.store_ = store;
	};

	this.getStore = function() {
		return this.store_;
	};

	this.setId = function( id ) {
		this.id_ = id;
	};

	this.getId = function() {
		return this.id_;
	};

	this.load = function() {
		this.getStore().get( 
			this.getId()
			, function( ok, value ) {
				if ( ok && value ) {
					JSON.parse( 
						new String( value ) 
						, function( key, value ) {
							if ( key ) {
								Util.valu( key, value );
							}
						}
					);
				}
			}
		);
	};

	this.save = function() {
		var bean = {};
		/* this will create the "bean" dynamicly */
		Util.walkNodes( 
			Util.id( this.getId() )
			, function( node ) { 
				return (
					Util.isTag( node, 'INPUT' ) 
					&& node.getAttribute( 'id' )
					&& Util.hasClass( node, 'durable' )
				); 
			}
			, function( node ) {
				var name = node.getAttribute( 'id' );
				/* FIXME: this is a little ... foul... */
				eval( 'bean.' + name + ' = \'' + node.value + '\';' );
			}
		);

		store.set( this.getId(), JSON.stringify( bean ) );
	};
 
	this.init = function( store, id ) {
		this.setStore( store );
		this.setId( id );
		this.load();
	};

	this.init( store, id );

};
